import pygame
from typing import Optional
from ..theme import Theme
from ..game import TypingGame
import os
from ..word_bank import WordBank
from ..user_profile import UserProfile

class StatsView:
    def __init__(self, screen: pygame.Surface, theme: Theme, word_bank: WordBank, user_profile: UserProfile):
        self.screen = screen
        self.theme = theme
        self.word_bank = word_bank
        self.user_profile = user_profile
        
        # 界面尺寸
        self.width = screen.get_width()
        self.height = screen.get_height()
        
        # 统计数据
        self.stats = {
            "total_words": 0,
            "mastered_words": 0,
            "accuracy": 0,
            "average_wpm": 0,
            "study_time": 0
        }
        
        # 加载统计数据
        self.load_stats()
        
        # 初始化游戏
        self.game = TypingGame()
        
        # 加载用户选择的词库
        self.load_selected_wordbank()
        
    def load_stats(self) -> None:
        """加载用户统计数据"""
        if self.user_profile.current_user:
            stats = self.user_profile.user_data.get("statistics", {})
            self.stats.update(stats)
    
    def load_selected_wordbank(self):
        """加载用户选择的词库"""
        try:
            # 尝试读取用户选择的词库
            wordbank_file = os.path.join("data", "user_data", "selected_wordbank.txt")
            if os.path.exists(wordbank_file):
                with open(wordbank_file, 'r') as f:
                    selected_wordbank = f.read().strip()
            else:
                selected_wordbank = "cet4"  # 默认使用四级词库
                
            # 加载词库
            if not self.game.load_wordbank(selected_wordbank):
                print(f"加载词库 {selected_wordbank} 失败，使用默认词库")
                self.game.load_wordbank("cet4")
        except Exception as e:
            print(f"加载词库失败: {str(e)}")
            self.game.load_wordbank("cet4")
        
    def handle_event(self, event: pygame.event.Event) -> Optional[str]:
        """处理事件
        
        Returns:
            str: 下一个视图的名称，如果返回 None 则继续显示当前视图
        """
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                return "menu"
        return None
        
    def draw(self) -> None:
        """绘制统计界面"""
        self.screen.fill(self.theme.background_color)
        
        # 绘制标题卡片
        title_card_rect = pygame.Rect(self.width/2 - 250, 30, 500, 80)
        self.theme.draw_card(self.screen, title_card_rect, with_shadow=True)
        
        # 绘制标题
        self.theme.draw_text(
            self.screen, 
            "学习统计", 
            (self.width/2, 70), 
            center=True, 
            size=36,
            color=self.theme.primary_color,
            shadow=True
        )
        
        # 如果没有用户，显示提示
        if not self.user_profile.current_user:
            info_card_rect = pygame.Rect(self.width/2 - 200, self.height/2 - 50, 400, 100)
            self.theme.draw_card(self.screen, info_card_rect, with_shadow=True)
            
            self.theme.draw_text(
                self.screen, 
                "请先选择或创建用户", 
                (self.width/2, self.height/2),
                center=True, 
                size=24,
                color=self.theme.text_color
            )
            return
        
        # 用户信息卡片
        user_card_rect = pygame.Rect(50, 130, self.width - 100, 100)
        self.theme.draw_card(self.screen, user_card_rect, with_shadow=True)
        
        # 显示用户名
        self.theme.draw_text(
            self.screen, 
            f"用户: {self.user_profile.current_user}",
            (user_card_rect.left + 50, user_card_rect.centery), 
            size=28,
            color=self.theme.primary_color
        )
        
        # 左侧统计卡片
        left_stats_card = pygame.Rect(50, 250, (self.width - 150) / 2, 280)
        self.theme.draw_card(self.screen, left_stats_card, with_shadow=True)
        
        # 显示个人统计数据
        self.theme.draw_text(
            self.screen, 
            "个人数据", 
            (left_stats_card.centerx, left_stats_card.top + 30),
            center=True, 
            size=24,
            color=self.theme.primary_color
        )
        
        stats_text = [
            f"总单词量: {self.stats['total_words']}",
            f"已掌握: {self.stats['mastered_words']}",
            f"正确率: {self.stats['accuracy']:.1f}%",
            f"平均速度: {self.stats['average_wpm']:.1f} WPM",
            f"学习时间: {self.stats['study_time']} 分钟"
        ]
        
        for i, text in enumerate(stats_text):
            self.theme.draw_text(
                self.screen, 
                text,
                (left_stats_card.left + 40, left_stats_card.top + 80 + i*40),
                size=20,
                color=self.theme.text_color
            )
        
        # 获取词库统计信息
        self.game.set_mode("study")  # 切换到学习模式以获取学习统计
        study_stats = self.game.get_stats()
        
        # 右侧词库统计卡片
        right_stats_card = pygame.Rect(left_stats_card.right + 50, 250, (self.width - 150) / 2, 280)
        self.theme.draw_card(self.screen, right_stats_card, with_shadow=True)
        
        # 显示词库统计标题
        self.theme.draw_text(
            self.screen, 
            "词库统计", 
            (right_stats_card.centerx, right_stats_card.top + 30),
            center=True, 
            size=24,
            color=self.theme.primary_color
        )
        
        # 重新排版词库统计数据，避免文字重叠
        wordbank_stats = [
            ("词库总词数", study_stats['total_words']),
            ("已学习词数", study_stats['learned_words']),
            ("已掌握词数", study_stats['mastered_words'])
        ]
        
        for i, (label, value) in enumerate(wordbank_stats):
            # 绘制标签
            self.theme.draw_text(
                self.screen,
                label,
                (right_stats_card.left + 40, right_stats_card.top + 80 + i*50),
                size=20,
                color=self.theme.text_color
            )
            
            # 绘制值（右对齐）
            self.theme.draw_text(
                self.screen,
                str(value),
                (right_stats_card.right - 40, right_stats_card.top + 80 + i*50),
                size=24,
                color=self.theme.primary_color
            )
        
        # 绘制进度条
        progress = study_stats['learned_words'] / max(1, study_stats['total_words'])
        progress_text = f"完成进度: {int(progress * 100)}%"
        
        progress_rect = pygame.Rect(
            right_stats_card.left + 40, 
            right_stats_card.top + 230, 
            right_stats_card.width - 80, 
            25
        )
        
        self.theme.draw_progress_bar(
            self.screen, 
            progress_rect, 
            progress, 
            progress_text
        )
        
        # 今日练习统计卡片
        practice_card = pygame.Rect(50, 550, self.width - 100, 150)
        self.theme.draw_card(self.screen, practice_card, with_shadow=True)
        
        # 获取练习统计
        self.game.set_mode("practice")  # 切换到练习模式以获取练习统计
        practice_stats = self.game.get_stats()
        
        # 显示练习统计标题
        self.theme.draw_text(
            self.screen, 
            "今日练习", 
            (practice_card.centerx, practice_card.top + 30),
            center=True, 
            size=24,
            color=self.theme.primary_color
        )
        
        # 显示练习数据
        practice_data = [
            ("练习单词数", practice_stats['completed_words']),
            ("完成进度", f"{practice_stats['progress_percentage']}%")
        ]
        
        # 在同一行显示数据，左右分布
        spacing = practice_card.width / len(practice_data)
        for i, (label, value) in enumerate(practice_data):
            x_pos = practice_card.left + spacing * i + spacing/2
            
            # 绘制标签
            self.theme.draw_text(
                self.screen,
                label,
                (x_pos, practice_card.top + 80),
                center=True,
                size=20,
                color=self.theme.text_color
            )
            
            # 绘制值
            self.theme.draw_text(
                self.screen,
                str(value),
                (x_pos, practice_card.top + 110),
                center=True,
                size=28,
                color=self.theme.primary_color
            )
        
        # 绘制操作提示卡片
        help_card_rect = pygame.Rect(20, self.height - 80, 180, 60)
        self.theme.draw_rounded_rect(
            self.screen, 
            help_card_rect, 
            (*self.theme.card_bg_color[:3], 200),  # 半透明
            border=1
        )
        
        # 绘制操作说明
        self.theme.draw_text(
            self.screen, 
            "按 Esc 返回主菜单",
            (help_card_rect.left + 20, help_card_rect.centery), 
            size=16,
            color=self.theme.text_color
        ) 